<template>
  <div class="user-center-container p-20px">
    <div class="user-center-header flex justify-center gap-24px flex-wrap" style="margin-top:1%;">
      <!-- 左侧：用户头像和基本信息卡 -->
      <ElCard class="user-info-card" :body-style="{ padding: '20px' }">
        <div class="user-info-header flex justify-center">
          <div class="avatar-container relative flex flex-col items-center">
            <div 
              @click="openDialog"
              class="avatar-placeholder flex justify-center items-center"
              v-if="!userInfoForm.userImages"
            ></div>
            
            <ElAvatar v-else :size="100" :src="userInfoForm.userImages" @click="previewAvatar" style="cursor: pointer" />
            <div class="avatar-actions absolute bottom-0 right-0 translate-x-1/4 translate-y-1/4">
              <ElButton 
                type="primary" 
                circle 
                size="small" 
                class="edit-avatar-btn"
                @click="openDialog"
                :icon="Edit"
              />
            </div>
          </div>
        </div>

          <ElDescriptions :column="1" border>
            <ElDescriptionsItem label="用户名称">
              {{ userInfo.userName || 'admin' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="手机号码">
              {{ userInfo.userPhone || '15888888888' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="电子邮箱">
              {{ userInfo.userEmail || 'ry@163.com' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="性别">
              <ElTag v-if="userInfo.userGender" type="primary">
                {{ userInfo.userGender === '1' ? '男' : '女' }}
              </ElTag>
              <span v-else>未设置</span>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="所属角色">
               <ElTag type="primary" v-for="role in userInfo.roles">
                {{role}}
               </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="最后登录时间">
              {{ userInfo.lastLoginTime || '2024-06-30 11:27:11' }}
            </ElDescriptionsItem>
              <ElDescriptionsItem label="最后登录IP">
              {{ userInfo.lastLoginIp || ''}}
            </ElDescriptionsItem>
          </ElDescriptions>
       
      </ElCard>

      <!-- 右侧：标签页内容 -->
      <ElCard style="width: 60%;">
        <ElTabs v-model="activeTab" class="user-tabs">
          <!-- 基本资料标签页 -->
          <ElTabPane label="基本资料" name="basic">
            <ElForm ref="userInfoFormRef" :model="userInfoForm" :rules="userInfoRules" label-width="100px">
              <ElFormItem label="用户名" prop="userName">
                <ElInput v-model="userInfoForm.userName" placeholder="请输入用户昵称" />
              </ElFormItem>
                 <ElFormItem label="性别" prop="userGender">
                <ElRadioGroup v-model="userInfoForm.userGender">
                  <ElRadio :label="'1'">男</ElRadio>
                  <ElRadio :label="'2'">女</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem label="用户昵称" prop="nickName">
                <ElInput v-model="userInfoForm.nickName" placeholder="请输入用户昵称" />
              </ElFormItem>
              <ElFormItem label="手机号码" prop="userPhone">
                <ElInput v-model="userInfoForm.userPhone" placeholder="请输入手机号码" />
              </ElFormItem>
              <ElFormItem label="邮箱" prop="userEmail">
                <ElInput v-model="userInfoForm.userEmail" placeholder="请输入邮箱" />
              </ElFormItem>
           
              <ElFormItem>
                <div class="form-actions">
                  <ElButton type="primary" @click="submitUserInfoChange">保存</ElButton>
                  <ElButton @click="resetUserInfoForm">关闭</ElButton>
                </div>
              </ElFormItem>
            </ElForm>
          </ElTabPane>
          
          <!-- 修改密码标签页 -->
          <ElTabPane label="修改密码" name="password">
            <ElForm ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
              <ElFormItem label="新密码" prop="newPassword">
                <ElInput v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
              </ElFormItem>
              <ElFormItem label="确认密码" prop="confirmPassword">
                <ElInput v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
              </ElFormItem>
              <ElFormItem>
                <div class="form-actions">
                  <ElButton type="primary" @click="submitPasswordChange">保存</ElButton>
                  <ElButton @click="resetPasswordForm">关闭</ElButton>
                </div>
              </ElFormItem>
            </ElForm>
          </ElTabPane>
        </ElTabs>
      </ElCard>
    </div>
  
    
    <!-- 素材选择对话框 -->
<el-dialog v-model="dialogVisible" title="选择素材" width="1000px" destroy-on-close>
      <manage :flag="mediaType" @selectImage="selectMedia" />
    </el-dialog>

    
    <!-- 图片预览组件 -->
    <ElImageViewer
      v-if="previewVisible"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="previewVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { ElCard, ElAvatar, ElDescriptions, ElDescriptionsItem, ElTag, ElButton, ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElRadioGroup, ElRadio, ElImageViewer, ElTabs, ElTabPane } from 'element-plus';
import { Edit } from '@element-plus/icons-vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { updateUser } from '@/service/api/system-manage';
import manage from "@/views/function/material/Image/index.vue"

const authStore = useAuthStore();

// 标签页控制
const activeTab = ref('basic');

// 用户信息
const userInfo = computed(() => authStore.userInfo);
console.log(userInfo.value);


// 素材选择对话框
const dialogVisible = ref(false);
const mediaType = ref(1); // 1=图片

// 图片预览
const previewVisible = ref(false);
const previewImages = ref<string[]>([]);
const previewIndex = ref(0);

// 表单相关
const { formRef: passwordFormRef, validate: validatePassword } = useForm();
const { formRef: userInfoFormRef, validate: validateUserInfo } = useForm();
const { defaultRequiredRule } = useFormRules();

// 密码表单数据
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
});

// 密码表单校验规则
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
};

// 用户信息表单数据
const userInfoForm = reactive({
  userName: '',
  userGender: undefined as string | undefined,
  nickName: '',
  userPhone: '',
  userEmail: '',
  userImages: computed(() => userInfo.value.userImages || '')
});


// 用户信息表单校验规则
const userInfoRules = {
  userName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '用户昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  userPhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

// 打开素材选择对话框
const openDialog = () => {
  dialogVisible.value = true;
};

// 选择媒体后的回调
const selectMedia = (url: string) => {
  dialogVisible.value = false;
  userInfo.value.userImages = url;
  ElMessage.warning('头像已更换，请保存用户信息以生效');
};

// 预览头像
const previewAvatar = () => {
  if (userInfoForm.userImages) {
    previewImages.value = [userInfoForm.userImages];
    previewIndex.value = 0;
    previewVisible.value = true;
  }
};

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
};
import { resetPassword} from '@/service/api';
// 提交密码修改
const submitPasswordChange = async () => {
    const params = {
      password: passwordForm.confirmPassword,
      userId:  userInfo.value.userId
    }
    
    await resetPassword(params);
    //提示成功
    ElMessage.success('密码重置成功');
    resetPasswordForm();

};

// 重置用户信息表单
const resetUserInfoForm = () => {
  userInfoForm.userName = userInfo.value.userName || '';
  userInfoForm.userGender = userInfo.value.userGender;
  userInfoForm.nickName = userInfo.value.nickName || '';
  userInfoForm.userPhone = userInfo.value.userPhone || '';
  userInfoForm.userEmail = userInfo.value.userEmail || '';
};

// 提交用户信息修改
const submitUserInfoChange = async () => {
  try {
    await validateUserInfo();
    
    // 调用修改用户信息的API
    const params = {
      id: userInfo.value.userId,
      userImages: userInfoForm.userImages,
      userName: userInfoForm.userName,
      userGender: userInfoForm.userGender,
      nickName: userInfoForm.nickName,
      userPhone: userInfoForm.userPhone,
      userEmail: userInfoForm.userEmail,
      status: userInfo.value.status,
      userRoles: userInfo.value.roles
    };
    
    const { error } = await updateUser(params);
    
    if (!error) {
      // 更新本地用户信息
      Object.assign(userInfo.value, {
        userName: userInfoForm.userName,
        userGender: userInfoForm.userGender,
        nickName: userInfoForm.nickName,
        userPhone: userInfoForm.userPhone,
        userEmail: userInfoForm.userEmail,
        userImages: userInfoForm.userImages
      });
      
      ElMessage.success('用户信息更新成功');
    }
  } catch (error) {
    console.error('用户信息更新失败:', error);
    ElMessage.error('用户信息更新失败');
  }
};


// 当组件挂载时确保用户数据已初始化并填充表单
onMounted(() => {
  authStore.initUserInfo();
  // 初始化表单数据
  resetUserInfoForm();
});
</script>


<style scoped lang="scss">
.user-center-container {
  min-height: 100%;
}

.user-info-card {
  width: 350px;
}

.title {
  margin-bottom: 20px;
  font-size: 24px;
}

.user-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 20px;
}

.user-details h3 {
  margin: 0 0 8px 0;
}

.user-details p {
  margin: 0 0 12px 0;
  color: #909399;
}

.user-roles {
  display: flex;
  gap: 8px;
}

.loading-state,
.error-state {
  padding: 40px;
  text-align: center;
}

.error-message {
  margin-bottom: 16px;
  color: #f56c6c;
}
</style>
